<template>
  <div class="content">
    <jc-button
      :btn-arr="['reload', 'remove', 'pass', 'sub', 'push', 'pushOrder', 'option', 'toExcel', 'batchFill', !list.length && 'check']"
      :disab-arr="['using', 'copy', 'freeze']"
      :fbillno="fbillNo"
      url="tSalOutstock/querySalOutList"
      @refresh="handleGetUntreated"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @forbidden="forbidden(1)"
      @startUsing="forbidden(2)"
      @cancellation="cancellation(1)"
      @NoCalncellation="cancellation(2)"
      @toExcel="handleExport"
      @del="delPublic"
      @pushDown="pushDown"
      @handleCom1="handleCom1(1)"
      @handleCom2="handleCom1(2)"
      @check="check('up')"
      @check1="check('down')"
      @pushOrder="pushOrder"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :sear-data1="searData1"
          :msg="tacitly"
          @seek="collect"
          @reload="handleGetUntreated"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        table-selection
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="particulars"
      >
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="particulars(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">
            {{ col.scope.row.fdocumentStatus }}
          </el-tag>
        </template>
        <template v-slot:billSlot="clo">
          <el-tag v-if="clo.scope.row.fcloseStatus==='A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fcloseStatus==='B'" type="danger">{{ $t('market.closed') }}</el-tag>
        </template>
      </jc-table>
      <cardTab :tab-arr="tabArr" @search="handleQueryBomList" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX" @change="orderWat">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  querySalOutList,
  salOutAudit,
  salOutUnAudit,
  salOutSubmit,
  salOutAuSubmit,
  salOutDelete,
  pushRet,
  pushToReceivable,
  salOutUnClose,
  salOutClose,
  cancelsalOut,
  unCancelsalOut, pushOutToNx
} from '@/api/marketManage/deliveryRelease'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  components: {
    cardTab: () => import('@/components/cardTab'),
    upDown: () => import('@/components/upDown'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    msg: {
      type: Number,
      default: 0
    },
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fentryData: [],
      ftype: 43,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      fbillNo: '',
      isdanjuDialog: false,
      orderLX: this.$t('menu.salesReturn'),
      receipts: [this.$t('menu.salesReturn'), this.$t('menu.receivable')], // 下推'销售退货单''应收单'
      billTypeData: [],
      fbillTypeId: 209,
      convert: this.$t('market.ckdth'), // '销售出库单至销售退货单'
      // 表头
      tableBorder: false,
      tabArr: [
        { label: '餐台', name: '1-1' },
        { label: '餐椅', name: '1-7' }
      ],
      tableData: [], // 销售数据
      tableHeader: [
        { label: this.$t('market.fdate'), prop: 'fdate', width: '100' },
        { label: this.$t('market.billNo'), type: 'tag', prop: 'fbillNo', width: '120' },
        { label: this.$t('market.cust'), prop: 'fcustomer', width: '120' },
        { label: this.$t('market.paezText1'), prop: 'fpaeztext', width: '110' },
        { label: this.$t('market.state'), type: 'state', prop: 'fdocumentStatus', width: '100' },
        { label: this.$t('market.closeState'), type: 'bill', prop: 'fcloseStatus', width: '80' },
        { label: this.$t('market.fmodel'), prop: 'fmodel', width: '120' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '130' },
        { label: this.$t('shop.fname2'), prop: 'fname', width: '120' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', width: '120' },
        { label: this.$t('market.mustqty'), prop: 'fmustqty', width: '100', align: 'right' },
        { label: this.$t('market.realqty'), prop: 'frealqty', width: '100', align: 'right' },
        { label: this.$t('market.camatcost'), prop: 'camatcost', align: 'right', width: '100' },
        { label: this.$t('market.fprice'), prop: 'fprice', width: '100', align: 'right' },
        { label: this.$t('market.ftaxPrice'), prop: 'ftaxprice', width: '100', align: 'right' },
        { label: this.$t('market.famount'), prop: 'famount', width: '100', align: 'right' },
        { label: this.$t('market.allamount'), prop: 'fallamount', width: '100', align: 'right' },
        { label: this.$t('market.averageprice'), prop: 'avgprice', width: '100', align: 'right' },
        { label: this.$t('market.avgpriceamount'), prop: 'avgpriceamount', width: '100', align: 'right' },
        { label: this.$t('market.payamount'), prop: 'payamount', width: '120', align: 'right' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200' }
      ],
      tableHeader1: [
        { label: this.$t('market.order'), prop: 'fsaleorderno' },
        { label: this.$t('market.chargeQty'), prop: 'fpriceunitqty' },
        { label: this.$t('market.topOrder'), prop: 'fsrcbillno' },
        { label: this.$t('market.xtshqty'), prop: 'fxtshqty' },
        { label: this.$t('market.returnqty'), prop: 'freturnqty' },
        { label: this.$t('market.stocker'), prop: 'fstocker' },
        { label: this.$t('market.stock2'), prop: 'fstock' },
        { label: this.$t('shop.salesman'), prop: 'fsalesman' },
        { label: this.$t('market.creator'), prop: 'fcreator' },
        { label: this.$t('market.createDate'), prop: 'fmodifyDate' },
        { label: this.$t('market.modifier'), prop: 'fmodifier' },
        { label: this.$t('market.modifyDate'), prop: 'fmodifyDate' },
        { label: this.$t('market.approver'), prop: 'fapprover' },
        { label: this.$t('market.approveDate'), prop: 'fapproveDate' },
        { label: this.$t('market.closeor'), prop: 'fcloser' },
        { label: this.$t('market.closeyDate'), prop: 'fcreateDate' },
        { label: this.$t('market.cancelleror'), prop: 'fcanceller' },
        { label: this.$t('market.cancellerDate'), prop: 'fcancelDate' },
        { label: this.$t('market.recCondition'), prop: 'freceiptcondition' },
        { label: this.$t('market.headDelivery'), prop: 'fheaddeliverywayname' },
        { label: this.$t('market.settleCurr'), prop: 'fsettlecurr' },
        { label: this.$t('market.settleType'), prop: 'fsettletype' },
        { label: this.$t('market.paezText'), prop: 'fpaeztext1' },
        { label: this.$t('market.paeztext4'), prop: 'fpaeztext2' },
        { label: this.$t('market.note'), prop: 'fnote' },
        { label: this.$t('market.note2'), prop: 'fnoteentry' },
        { label: 's/o', prop: 'fpaeztext3' },
        { label: this.$t('market.tax'), prop: 'fisincludedtax' },
        { label: this.$t('market.cancelstatus'), prop: 'fcancelstatus' },
        { label: this.$t('market.localCurr'), prop: 'flocalcurr' },
        { label: this.$t('market.exchangeRate'), prop: 'fexchangerate' },
        { label: this.$t('market.exchangeType'), prop: 'fexchangetype' },
        { label: this.$t('market.priceList'), prop: 'fpricelist' },
        { label: this.$t('market.billtaxamount'), prop: 'fbilltaxamount' },
        { label: this.$t('market.billtaxamount_lc'), prop: 'fbilltaxamount_lc' },
        { label: this.$t('market.billamount'), prop: 'fbillamount' },
        { label: this.$t('market.billamount_lc'), prop: 'fbillamount_lc' },
        { label: this.$t('market.billallamount'), prop: 'fbillallamount' },
        { label: this.$t('market.billallamount_lc'), prop: 'fbillallamount_lc' }
      ],
      searData1: []
    }
  },
  created() {
    const end = this.gettimeEnd()
    const start = this.gettimeStart()
    const trueFsaler = this.$route.query.fsaler
    trueFsaler && this.searData1.push(
      { fenglish: 'fsaler', val: this.$route.query.fsaler, fid: 7 },
      { fenglish: 'fdate', val: trueFsaler ? [start, end] : '', fid: 7 },
      { fenglish: 'fdocumentStatus', val: trueFsaler ? 'C' : '', fid: 7 }
    )
    this.searData1.length === 0 ? this.handleGetUntreated() : ''
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          querySalOutList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '销售出库列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取销售价目列表数据
    async handleGetUntreated(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      this.searCollData = this.searCollData.concat(this.details)
      this.searCollData.forEach(res => {
        if (res.field === 'fdate') {
          this.fdate = res.seach
        }
      })
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        fdate: this.fdate,
        search: this.searCollData
      }
      const { data: RES, data: total } = await querySalOutList(DATA)
      this.tableData = RES.array.map(item => {
        return (toMxAmina(item))
      })
      this.total = total.total
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList(ev) {
      this.searCollData = []
      this.currentPage = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 价目详情
    particulars(ev) {
      const id = ev.fid
      if (this.msg === 0) {
        this.$router.push({ path: `/editOutBank/${id}` })
      } else {
        this.$emit('outBank', id)
      }
    },
    // 全选
    handleSelectAll(val) {
      this.fbillNo = val[0].fbillNo
      this.selectVal = []
      this.fentryData = []
      this.fidsData = []
      val.forEach(item => {
        item.fbillNo && this.selectVal.push(item.fbillNo)
        this.fentryData.push(item.fentryId)
        this.fidsData.push(item.fid)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 下推出库单
    pushDown() {
      this.isdanjuDialog = true
      this.orderLX = this.$t('menu.salesReturn')
      this.convert = this.$t('market.ckdth')
      this.fbillTypeId = 209
      this.purpoorder('SX_RETURNSTOCK')
    },
    orderWat(ev) {
      if (ev === this.$t('menu.salesReturn')) {
        this.purpoorder('SX_RETURNSTOCK')
        this.convert = this.$t('market.ckdth')
        this.fbillTypeId = 209
      } else if (ev === this.$t('menu.receivable')) {
        this.purpoorder('SX_FRECEIVABLE_BILLTYPE')
        this.convert = this.$t('market.ckdyc')
        this.fbillTypeId = 1262
      } else if (ev === this.$t('menu.proceeds')) {
        this.purpoorder('SX_RECEIPT_BILLTYPE')
        this.convert = this.$t('market.ckdck') // '销售出库单至收款单'
        this.fbillTypeId = 1266
      }
    },
    // 采购订单单据
    async purpoorder(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    },
    // 下推出库单
    pushDownOrder() {
      const DATA = {
        SoucrceIds: this.fidsData,
        EntryIds: this.fentryData,
        fbillTypeId: this.fbillTypeId
      }
      if (this.orderLX === this.$t('menu.salesReturn')) {
        pushRet(DATA).then(RES => {
          if (RES.code === 0) {
            this.$router.push({
              path: `/editSaleReturn/${RES.data}`
            })
          } else {
            this.$confirm(RES.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.receivable')) {
        pushToReceivable(DATA).then(RES => {
          if (RES.code === 0) {
            this.$router.push({
              path: `/receivableDetail/${RES.data.fid}`
            })
          } else {
            this.$confirm(RES.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
      this.isdanjuDialog = false
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? salOutSubmit : salOutAuSubmit
      this.toExamineFun(api)
    },
    // 审核
    async audit(ev) {
      const api = ev === 1 ? salOutAudit : salOutUnAudit
      this.toExamineFun(api)
    },
    // 关闭
    async forbidden(ev) {
      const api = ev === 1 ? salOutClose : salOutUnClose
      this.toExamineFun(api)
    },
    // 作废
    async cancellation(ev) {
      const api = ev === 1 ? cancelsalOut : unCancelsalOut
      this.toExamineFun(api)
    },
    // 删除
    delPublic() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = salOutDelete
        this.toExamineFun(api)
      })
    },
    // 推送至惠州杰希销售订单
    pushOrder() {
      const DATA = { SoucrceIds: this.fidsData }
      pushOutToNx(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message + res.data, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 上查、下查
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 套打
    handleCom1(ev) {
      const id = this.selectVal.join(',')
      if (ev === 1) { // 通用
        this.$router.push({ path: `/deliveryTong1/${id}` })
      } else { // 连续
        this.$router.push({ path: `/deliveryLian1/${id}` })
      }
    },
    // 本月第一天
    gettimeStart() {
      const nowdays = new Date()
      let year = nowdays.getFullYear()
      let month = nowdays.getMonth()
      if (month === 0) {
        month = 12
        year = year - 1
      } else if (month < 10) {
        month = '0' + Number(month + 1)
      } else {
        month = Number(month + 1)
      }
      let firstDayOfPreMonth = year + '-' + month + '-' + '01'
      firstDayOfPreMonth = firstDayOfPreMonth.toString()
      return new Date(firstDayOfPreMonth)
    },
    // 本月最后一天
    gettimeEnd() {
      const nowdays = new Date()
      let year = nowdays.getFullYear()
      let month = nowdays.getMonth()
      if (month === 0) {
        month = 12
        year = year - 1
      } else if (month < 10) {
        month = '0' + Number(month + 1)
      } else {
        month = Number(month + 1)
      }
      const lastDay = new Date(year, month, 0)
      let lastDayOfPreMonth = year + '-' + month + '-' + lastDay.getDate()
      lastDayOfPreMonth = lastDayOfPreMonth.toString()
      return new Date(lastDayOfPreMonth)
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;

  .el-table1 {
    border: 1px solid #ccc;

    &::v-deep th {
      background: #f5f7fa;
      border-right: none;
      //border-color: #ccc;
      border-color: #ccc;
    }

    &::v-deep th:last-child {
      border-right: none;
    }

    &::v-deep th.is-leaf {
      border-color: #ccc;
    }

    &::v-deep td {
      background: #f5f7fa;

      border-right: none;
      border-bottom: none;
      padding: 3px 0;
      border-color: #ccc;
    }

    td:last-child {
      border-right: none;
    }
  }

  .header {
    position: relative;

    .header-name {
      width: 100%;
    }

    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
